var optionsDatepickers = {
    dateFormat: 'dd-mm-yy',
    dayNamesMin: ['do', 'lu', 'ma', 'mi', 'ju', 'vi', 'sá'],
    dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
    monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'],
    monthNamesShort:['Ene','Feb','Mar','Abril','Mayo','Jun','Jul','Ago','Sept','Oct','Nov','Dic'],
    prevText : '<i class="fa fa-chevron-left"></i>',
    nextText : '<i class="fa fa-chevron-right"></i>'
}
, imagesInOrder = false, superboxItem;

$(document).ready(function () {
    superboxItem = $('#superboxItem').val();
    $('#left-panel li[data-nav="about-me"]').addClass('active');
    boxes();
    summernoteInit();
    //fechaPicker();
    ajaxFileUpload();
    ajaxImagenHomeUpload();
    //tags();
    $('.images-upload').find('.superbox-list:hidden').show();
    cargarVideo();
    $('.images-upload').sortable();
    $('.saveForm').click(function () {$('form:first').submit()})
    $('form:first').submit(function () {
        if (!imagesInOrder) {
            ordenarImagenes();
            return false
        } else {
            var code = $('.summernote').code();
            var newCode = $('<div></div>').append(code)
                    .find('iframe').wrap('<div class="flex-video"/>').end()
                    .find('img').removeAttr('style').end()
                    .html();
            $('textarea[name="contenido"]').val(newCode);
            return true;
        }
    });
    $('.vista-previa').each(function (){
        if ($(this).find('img').attr('src') != 'img/uploader-background2.jpg') {
            $(this).find('a').show();
        }
    })
    $('.vista-previa a').click(function () {
        var $this = $(this);
        $.ajax({
            url:BASE_URL+'php/controllers/borrarThumb.controller.php',
            type:'post',
            data:{src:$this.attr('data-src'), type:$this.attr('data-type')},
            success: function () {
                $this.parent().find('img')
                .fadeOut(400, function() {
                    $this.parent().find('img').attr('src', 'img/uploader-background2.jpg');
                })
                .fadeIn(400, function () {
                    $this.hide();
                })
            }
        })
    })
})

function forceUpload () {
    $('#mySubmit').trigger('click');
}

function summernoteInit () {
    $('.summernote').summernote({
        lang:'es-ES',
        height : 300,
        focus : false,
        tabsize : 2,
        toolbar: [     
            ['style', ['bold', 'italic', 'underline', 'clear']],
            ['color', ['color']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['Insert', ['link', 'picture', 'video']]
        ],
        onImageUpload: function(files, editor, welEditable) {
            sendFile(files[0], editor, welEditable);
        }
    });
}

function sendFile(file, editor, welEditable) {
    var data = new FormData();
    data.append("file", file);
    $.ajax({
        data: data,
        type: "POST",
        url: BASE_URL+'php/uploaders/summernote.uploader.php',
        cache: false,
        contentType: false,
        processData: false,
        success: function(url) {
            editor.insertImage(welEditable, url);
        }
    });
}

function fechaPicker () {
    $('input[name="fecha"]').datepicker(optionsDatepickers)
}

//IMAGENES

//cargar
function ajaxFileUpload () {
    var html, replacer = new Replacer();
    $('#imagesUploader').ajaxForm({
        beforeSend: function() {
            $('#images-uploader .widget-toolbar, #images-uploader .jarviswidget-loader').show();
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            $('#images-uploader .widget-toolbar .progress').attr('data-original-title', percentVal);
            $('#images-uploader .progress-bar').width(percentVal).html(percentVal);
        },
        success: function (data) {
            if (data) {
                html = superboxItem;
                html = replacer.listReplace(html, data);
                $('.images-upload').append(html).find('.superbox-list:hidden').fadeIn();
            }
            $( '.images-upload' )
            .sortable( 'destroy' )
            .sortable({
                start: function(e, ui){
                    ui.placeholder.height(1);
                }
            });
            $('#images-uploader .widget-toolbar, #images-uploader .jarviswidget-loader').hide();
            $('#images-uploader .widget-toolbar .progress').attr('data-original-title', '0%');
            $('#images-uploader .progress-bar').width('0%').html('0%');
        }
    });
}

//ordenar
function ordenarImagenes () {
    var data = '', id;
    $('.images-upload .sortable').each(function (i) {
        data += '&orden[]='+i;
        data += '&id[]='+$(this).attr('data-id');
    })
    $.ajax({
        type:'POST',
        url:BASE_URL+'php/controllers/ordenar.controller.php',
        data: 'tabla=imagen'+data,
        success:function () {
            imagesInOrder = true;
            $('form:first').submit();
        }
    })    
}

//borrar
function borrarImagen (id) {
    borrarModalInit();
    $('#myModal').modal('show');
    $('#myModal #modalAction').click(function () {
        $('#myModal .modal-footer button').unbind('click');
        loaderModalInit();
        $.ajax({
            type:'post',
            url: BASE_URL+'php/controllers/borrarImagen.controller.php',
            data:{id:id},
            success: function () {
                $('#myModal').modal('hide');
                $('.sortable[data-id="'+id+'"]').fadeOut(
                    500,
                    function () {
                        $('.sortable[data-id="'+id+'"]').remove();
                    }
                )
                    
            }
        })
    })
}

//cargar
function forceImagenUpload () {
    $('#imagenSubmit').trigger('click');
}
function ajaxImagenHomeUpload () {
    $('#imagenUploader').ajaxForm({
        success: function (data) {
            if (data) {
                $('.imagenUploader img')
                .fadeOut(400, function() {
                    $('.imagenUploader img').attr('src', data[0].src);
                })
                .fadeIn(400, function () {
                    $('.imagenUploader a').attr('data-src', data[0].src).show();
                });
            }
        }
    });
}
//--FIN IMAGENES--

function tags () {
    var cache = {}
    $('#tags').tagsInput({
        autocomplete_url: BASE_URL+'php/controllers/autocomplete.controller.php',
        autocomplete:{
            minLength: 2,
            source: function( request, response ) {
                var term = request.term;
                if ( term in cache ) {
                    response( cache[ term ] );
                    return;
                }
                $.getJSON( BASE_URL+'php/controllers/autocomplete.controller.php', request, function( data, status, xhr ) {
                    cache[ term ] = data;
                    response( data );
                })
            },
            appendTo: '#myAutocompleContainer'
        },
        height:'80px',
        width:'99%',
        defaultText: '',
        delimiter:'|',
        onAddTag: function () {
            $('#tags_tag').autocomplete( "close" )
        }
    })
}

//cargar video
function cargarVideo () {
    var html, video, replacer = new Replacer();
    $('.cargarVideo').click(function () {
        cargarVideoModalInit();
        $('#myModal').modal('show');
        $('#myModal #modalAction').click(function () {
            $('#myModal .modal-footer button').unbind('click');
            video = $('#myModal input[name="video"]').val();
            loaderModalInit();
            $.ajax({
                type:'post',
                url: BASE_URL+'php/uploaders/publicacionVideo.uploader.php',
                data:{video:video, imgprefix:$('#imagesUploader input[name="imgprefix"]').val()},
                success: function (data) {
                    $('#myModal').modal('hide');
                    html = superboxItem;
                    html = replacer.listReplace(html, data);
                    $('.images-upload').append(html).find('.superbox-list:hidden').fadeIn();
                }
            })
        })
    })
}


//modals
function borrarModalInit () {
    $('#myModal #myModalLabel .text').html('Borrar Imagen');
    $('#myModal #myModalLabel .jarviswidget-loader').hide();
    $('#myModal .modal-body p').html('¿Está seguro que desea borrar esta imagen?');
    $('#myModal #modalAction').html('Borrar').addClass('btn-danger');
    $('#myModal .modal-footer button').attr('disabled', false);
}

function loaderModalInit () {
    $('#myModal #myModalLabel .jarviswidget-loader').show();
    $('#myModal .modal-body p').html('Por favor espere...');
    $('#myModal .modal-footer button').attr('disabled', true);
}

function cargarVideoModalInit () {
    $('#myModal #myModalLabel .text').html('Cargar Video');
    $('#myModal #myModalLabel .jarviswidget-loader').hide();
    $('#myModal .modal-body p').html('<form class="smart-form"><label class="input"><input type="text" name="video" value="" placeholder="Ej.: https://www.youtube.com/watch?v=v1uyQZNg2vE" /></label></form>');
    $('#myModal #modalAction').html('Cargar').addClass('btn-success');
    $('#myModal .modal-footer button').attr('disabled', false);
}

function boxes () {
    if (document.location.hash == '#success') boxSuccess('La información se modificó con éxito');
}